# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 15:34:24 2020

@author: wsr
"""
import argparse
import json
from typing import Dict, List, Set

import pypinyin
import mwclient

HOST = 'lgqm.huijiwiki.com'

with open('ignored_members.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    IGNORED_MEMBERS: Dict[str,
                          Set[str]] = {key: set(data[key])
                                       for key in data}


def login(username: str, password: str, host=HOST) -> mwclient.Site:
    print(username, password)
    site = mwclient.Site(host)
    site.login(username, password)
    assert site.logged_in
    return site


def query_category_members(site: mwclient.Site,
                           cate_name: str) -> Dict[str, List[str]]:
    members: Dict[str, List[str]] = dict()
    for member in site.categories[cate_name]:
        name = member.name
        if cate_name in IGNORED_MEMBERS and name in IGNORED_MEMBERS[cate_name]:
            continue
        initial = pypinyin.pinyin(name,
                                  style=pypinyin.FIRST_LETTER)[0][0].upper()
        if initial not in members:
            members[initial] = list()
        members[initial].append(name)
    return members


def sync_template(site: mwclient.Site, temp_name: str,
                  members: Dict[str, List[str]]):
    page: mwclient.page.Page = site.pages['模板:' + temp_name]
    text = page.text()
    print(text)
    lines: List[str] = text.split('\n')
    for i, line in enumerate(lines):
        if 'group' in line:
            break
    new_lines = lines[:i]
    for i, initial in enumerate(members):
        idx = i + 1
        new_lines.append(f'| group{idx} = {initial}')
        new_lines.append(f'| list{idx} =')
        for member_name in members[initial]:
            new_lines.append(f'* [[{member_name}]]')
    new_lines.append('}}\n')
    new_text = '\n'.join(new_lines)
    page.save(new_text)


def login_n_sync(username, password, template):
    site = login(username, password)

    members = query_category_members(site, template)
    print(members)
    sync_template(site, template, members)


def main():
    parser = argparse.ArgumentParser(
        description='同步wiki页面分类:template到模板:template')
    parser.add_argument('-n',
                        '--name',
                        dest='username',
                        type=str,
                        required=True,
                        help='用户名')
    parser.add_argument('-p',
                        '--pass',
                        dest='password',
                        type=str,
                        required=True,
                        help='密码')
    parser.add_argument('template', help='需要同步的模板名', type=str)
    args = parser.parse_args()
    login_n_sync(args.username, args.password, args.template)


if __name__ == "__main__":
    main()
